package com.learning.spring.ioc.property.security;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * ClassName: DesUtil
 * Description: DES 加密解密工具类（对称加密）
 * Date: 2018/8/7 16:45 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class DesUtil {
    private static Key key;

    private static final String KEY_STR = "MyKEY";
    private static final String DES = "DES";

    static {
        try {
            KeyGenerator generator = KeyGenerator.getInstance(DES);
            generator.init(new SecureRandom(KEY_STR.getBytes()));
            key = generator.generateKey();
            generator = null;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 对字符串进行DES加密，返回BASE64编码的加密字符串
     *
     * @param str
     * @return
     */
    public static String encrypt(String str) {
        BASE64Encoder base64Encoder = new BASE64Encoder();
        try {
            byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
            Cipher cipher = Cipher.getInstance(DES);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] encryptBytes = cipher.doFinal(bytes);
            return base64Encoder.encode(encryptBytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 对BASE64编码的加密字符串进行解密，返回解密后的字符串
     *
     * @param str
     * @return
     */
    public static String decrypt(String str) {
        BASE64Decoder base64Decoder = new BASE64Decoder();
        try {
            byte[] bytes = base64Decoder.decodeBuffer(str);
            Cipher cipher = Cipher.getInstance(DES);
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] decryptBytes = cipher.doFinal(bytes);
            return new String(decryptBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
